package org.elephas.webapp.backend.component.management;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxFallbackDefaultDataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.elephas.model.Blog;
import org.elephas.service.Elephas;
import org.elephas.webapp.frontend.validator.UniqueBlogNameValidator;
import org.elephas.webapp.model.DetachableBlogModel;

public class ApplicationAdminPanel extends Panel {
	private static final long serialVersionUID = 1L;

	public ApplicationAdminPanel(String id) {
		super(id);

		List<IColumn> columns = new ArrayList<IColumn>();
		columns.add(new PropertyColumn(new Model("ID"), "uuid"));
		columns.add(new PropertyColumn(new Model("Name"), "name"));
		columns
				.add(new PropertyColumn(new Model("Description"), "description"));

		add(new AjaxFallbackDefaultDataTable("table", columns,
				new SortableBlogDataProvider(), 10));

		add(new BlogForm("form"));
		add(new FeedbackPanel("formFeedback"));
	}

	/**
	 * This form can be used to add new blogs or edit existing ones.
	 * 
	 * @author Gerolf Seitz
	 * 
	 */
	class BlogForm extends Form {

		private static final long serialVersionUID = 1L;

		@SpringBean
		private Elephas elephas;

		public BlogForm(String id) {
			this(id, new DetachableBlogModel());
		}

		public BlogForm(String id, DetachableBlogModel model) {
			super(id, new CompoundPropertyModel(model));
			add(new RequiredTextField("name")
					.add(new UniqueBlogNameValidator()));
			add(new TextArea("description"));
		}

		@Override
		protected void onSubmit() {
			Blog blog = ((Blog) getModelObject());
			elephas.saveBlog(blog);
			setModel(new CompoundPropertyModel(new DetachableBlogModel()));
		}
	}
}
